﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace System.Windows.Controls
{
    public static class ControlsExtensions
    {
        public static void ExpandAll(this TreeView treeView)
        {
            ExpandAllItems(treeView, treeView, true);
        }

        public static void CollapseAll(this TreeView treeView)
        {
            ExpandAllItems(treeView, treeView, false);
        }
        private static void ExpandAllItems(TreeView treeView, ItemsControl control, bool expand)
        {
            if (control == null)
            {
                return;
            }

            foreach (var item in control.Items)
            {
                if (item is TreeViewItem tvi)
                {
                    if (tvi.HasItems)
                    {
                        tvi.IsExpanded = expand;
                        ExpandAllItems(treeView, tvi, expand);
                    }
                }
                //var c = control.ItemContainerGenerator.ContainerFromItem(item);
                //if (c is TreeViewItem tvi)
                //{
                //    if (tvi.HasItems)
                //    {
                //        tvi.IsExpanded = expand;
                //        ExpandAllItems(treeView, tvi, expand);
                //    }
                //}
            }
        }
    }
}
